package com.geek.novel.utils

import com.google.gson.*
import com.google.gson.JsonParseException
import java.lang.reflect.Type
import java.text.DateFormat
import java.util.*


object GsonUtil {

    class DateSerializer : JsonSerializer<Date>, JsonDeserializer<Date> {
        override fun serialize(src: Date, typeOfSrc: Type, context: JsonSerializationContext): JsonElement {
            return JsonPrimitive(src.time)
        }
        override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Date {
            return Date(json.asJsonPrimitive.asLong)
        }
    }

    private val gson = GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create()
    fun <T> fromJson(target: JsonElement, cls: Class<T>): T{
        return gson.fromJson(target, cls)
    }
    fun <T> fromJsonList(target: JsonArray, cls: Class<T>): List<T>{
        return target.map { gson.fromJson(it, cls) }
    }
    fun <T> fromJson(target: String, cls: Class<T>): T{
        if(target.startsWith("{")){
            return gson.fromJson(target, cls)
        }
        throw RuntimeException("Json格式化异常：$target")
    }
    fun toJson(target: Any): String{
        return gson.toJson(target)
    }
    fun toJsonTree(src: Any): JsonElement {
        return gson.toJsonTree(src)
    }


    private val gsonTime = GsonBuilder()
        .registerTypeAdapter(Date::class.java, DateSerializer()).setDateFormat(DateFormat.LONG)
        .create()

    fun toJsonTime(target: Any): String{
        return gsonTime.toJson(target)
    }

}